<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目" prop="projectId">
              <!-- <el-input v-model="queryParams.projectId" placeholder="请输入项目" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.projectId" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="([key, value], index) in Object.entries(projectList)"
                  :key="key"
                  :label="value"
                  :value="key"
                  @keyup.enter="handleQuery"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="版本号" prop="versionName">
              <el-input v-model="queryParams.versionId" placeholder="请输入版本号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['pm:version:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['pm:version:export']">导出</el-button>
          </el-col>

          <!-- <el-col :span="1.5">
              <el-button type="warning" plain  @click="handleUpdate()"
              v-hasPermi="['pm:milestone:edit']">修改</el-button>
            </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange" fit show-overflow-tooltip>
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="主键" align="center" prop="id" v-if="true" /> -->
        <el-table-column v-if="columns[0].visible" label="租户编号" align="center" prop="tenantId" />
        <el-table-column v-if="columns[1].visible" label="项目" align="center" prop="projectId" width="200">
          <template #default="scope">
            <el-tag v-for="[key, value] in filteredRequireList(projectList, scope.row.projectId)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="版本号" align="center" prop="versionId" width="200">
          <template #default="scope">
            <el-tag :style="{ color: scope.row.classStyle }">{{ scope.row.versionId }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="排序" align="center" prop="versionSort" />
        <el-table-column v-if="columns[4].visible" label="关联人员" align="center" prop="relatedUsers"> </el-table-column>
        <el-table-column v-if="columns[5].visible" label="发布状态" align="center" prop="isPublished" width="200">
          <template #default="scope">
            <span>{{ scope.row.status == 0 ? '正常' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[12].visible" label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[13].visible" label="截止时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[14].visible" label="耗时" align="center" prop="costTime" width="100" />
        <el-table-column v-if="columns[6].visible" label="创建部门" align="center" prop="createDeptName" />
        <el-table-column v-if="columns[7].visible" label="创建者" align="center" prop="createByName" />
        <el-table-column v-if="columns[8].visible" label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[9].visible" label="修改者" align="center" prop="updateByName" />
        <el-table-column v-if="columns[10].visible" label="修改时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[11].visible" label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="300px">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handView(scope.row)">预览</el-button>

            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pm:version:edit']">修改</el-button>

            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pm:version:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改小目标对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="versionFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" filterable placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(projectList)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 新版本号下拉框 -->
          <el-col :span="12">
            <!-- 版本号 -->
            <el-form-item label="版本号">
              <div class="version-selectors">
                <!-- 主版本号 -->
                <el-select v-model="taskForm.majorVersion" filterable placeholder="主版本号" class="version-selector">
                  <el-option v-for="num in versionNumbers" :key="num" :label="num" :value="num"></el-option>
                </el-select>
                <span class="version-separator">.</span>
                <!-- 次版本号 -->
                <el-select v-model="taskForm.minorVersion" filterable placeholder="次版本号" class="version-selector">
                  <el-option v-for="num in versionNumbers" :key="num" :label="num" :value="num"></el-option>
                </el-select>
                <span class="version-separator">.</span>
                <!-- 修订号 -->
                <el-select v-model="taskForm.patchVersion" filterable placeholder="修订号" class="version-selector">
                  <el-option v-for="num in versionNumbers" :key="num" :label="num" :value="num"></el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="versionSort">
              <el-input v-model="form.versionSort" placeholder="请输入排序" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="关联人员" prop="relatedUsers">
                <el-input v-model="form.relatedUsers" placeholder="请输入关联人员" />
              </el-form-item> -->
            <el-form-item label="关联人员">
              <el-select v-model="form.relatedUsers" filterable multiple placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本号颜色">
              <el-select v-model="form.classStyle" placeholder="请选择颜色">
                <el-option v-for="dict in pm_color" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布状态">
              <el-radio-group v-model="form.isPublished">
                <el-radio v-for="dict in pm_project_release" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.startDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.endDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择截止时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看版本号对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.viewVisible" append-to-body>
      <el-form ref="versionFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-input v-model="form.projectId" placeholder="请输入项目" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="versionName">
              <el-input v-model="form.versionId" placeholder="请输入版本号" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="versionSort">
              <el-input v-model="form.versionSort" placeholder="请输入排序" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联人员" prop="roleIds">
              <el-select v-model="form.relatedUsers" filterable multiple placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value" :value="key"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status" disabled>
                <el-radio v-for="dict in pm_project_release" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建部门">
              <el-input v-model="form.createDeptName" placeholder="请输入创建部门" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.startDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker
                style="width: 400px"
                clearable
                v-model="form.endDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择截止时间"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建者">
              <el-input v-model="form.createByName" placeholder="请输入创建者" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-input v-model="form.createTime" placeholder="请输入创建时间" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="修改者">
              <el-input v-model="form.updateByName" placeholder="修改者" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间">
              <el-input v-model="form.updateTime" placeholder="请输入创建时间" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="耗时" prop="costTime">
              <el-input v-model="form.costTime" placeholder="请输入耗时" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" readonly></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Version" lang="ts">
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pm_project_release, sys_user_sex } = toRefs<any>(proxy?.useDict('pm_project_release', 'sys_user_sex'));
const { pm_color } = toRefs<any>(proxy?.useDict('pm_color'));
import { listVersion, getVersion, delVersion, addVersion, updateVersion } from '@/api/pm/version/index';
import { VersionVO, VersionQuery, VersionForm } from '@/api/pm/version/types';
import { RoleVO } from '@/api/system/role/types';
import api from '@/api/system/user/index';
const postOptions = ref([]);
const roleOptions = ref<RoleVO[]>([]);
const projectList = ref([]);
const versionList = ref<VersionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const isTooltipVisible = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const versionFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  viewVisible: false
});
// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `租户编号`, visible: false, children: [] },
  { key: 1, label: `项目`, visible: true, children: [] },
  { key: 2, label: `版本号`, visible: true, children: [] },
  { key: 3, label: `排序`, visible: false, children: [] },
  { key: 4, label: `关联人员`, visible: false, children: [] },
  { key: 5, label: `发布状态`, visible: true, children: [] },
  { key: 6, label: `创建部门`, visible: false, children: [] },
  { key: 7, label: `创建者`, visible: false, children: [] },
  { key: 8, label: `创建时间`, visible: false, children: [] },
  { key: 9, label: `修改者`, visible: false, children: [] },
  { key: 10, label: `修改时间`, visible: false, children: [] },
  { key: 11, label: `备注`, visible: true, children: [] },
  { key: 12, label: `开始时间`, visible: true, children: [] },
  { key: 13, label: `截止时间`, visible: true, children: [] },
  { key: 14, label: `耗时`, visible: true, children: [] }
]);
const initFormData: VersionForm = {
  id: undefined,
  tenantId: undefined,
  projectId: undefined,
  versionId: undefined,
  versionSort: undefined,
  relatedUsers: undefined,
  isPublished: undefined,
  classStyle: undefined,
  remark: undefined,
  createByName: undefined,
  updateByName: undefined,
  createDeptName: undefined
};
const data = reactive<PageData<VersionForm, VersionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    tenantId: undefined,
    projectId: undefined,
    versionId: undefined,
    relatedUsers: undefined,
    isPublished: undefined,
    params: {}
  },
  rules: {
    projectId: [{ required: true, message: '项目不能为空', trigger: 'change' }],
    versionId: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    isPublished: [{ required: true, message: '发布状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询版本号列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.isAsc = 'desc';
  queryParams.value.orderByColumn = 'id';
  console.log('参数', queryParams.value);
  const res = await listVersion(queryParams.value);
  versionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  versionFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: VersionVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加版本号';
  // 获取目标关联人
  const data1 = await api.affiliatePperson('user');
  postOptions.value = data1.data;
  const data2 = await api.affiliatePperson('project');
  projectList.value = data2.data;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: VersionVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getVersion(_id);
  res.data.relatedUsers = JSON.parse(res.data.relatedUsers);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改版本号';
  const data1 = await api.affiliatePperson('user');
  postOptions.value = data1.data;
  const data2 = await api.affiliatePperson('project');
  projectList.value = data2.data;
};

/** 预览按钮操作 */
const handView = async (row?: VersionVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getVersion(_id);
  res.data.relatedUsers = JSON.parse(res.data.relatedUsers);
  Object.assign(form.value, res.data);
  dialog.viewVisible = true;
  dialog.title = '预览版本号';
  const data1 = await api.affiliatePperson('user');
  postOptions.value = data1.data;
};

/** 提交按钮 */
const submitForm = () => {
  versionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.relatedUsers = JSON.stringify(form.value.relatedUsers);
      if (form.value.id) {
        await updateVersion(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addVersion(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: VersionVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除版本号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delVersion(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'pm/version/export',
    {
      ...queryParams.value
    },
    `version_${new Date().getTime()}.xlsx`
  );
};
const filteredRequireList = (data, projectId: string | number) => {
  return Object.entries(data).filter(([key]) => key === projectId);
};
const allList = async () => {
  const data2 = await api.affiliatePperson('project');
  projectList.value = data2.data;
};

onMounted(() => {
  getList();
  allList();
});
//表单数据
const taskForm = ref({
  majorVersion: null, //主版本号
  minorVersion: null, //次版本号
  patchVersion: null //修订号
});
//版本号选择
const versionNumbers = ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); //可根据需求调整
</script>
<style>
.version-selectors {
  display: flex;
  align-items: center;
}

.version-selector {
  width: 102px; /* 每个下拉框宽度为 80px */
}

.version-separator {
  margin: 0 8px;
  font-size: 16px;
  font-weight: bold;
}
</style>
